<template>
  <div id="map" className="map">

  </div>
</template>

<script>
window._AMapSecurityConfig = {
  securityJsCode: '652541c3a3d61db3cfc900ffa7d9e124'
}

import AMapLoader from '@amap/amap-jsapi-loader'
import $ from 'jquery'
import { mapGetters } from 'vuex'
import { colors } from '../../utils/mapSettings'
import { citys, citys2 } from '../../utils/citys'

export default {
  name: 'Map2',
  props: {
    showPosition: Function
  },
  data() {
    return {
      //当前是否为城市
      isCity: false,
      //地图模块
      map: null,
      //地图显示模块
      district: null,
      polygon: null,
      polygon2: null,
      //绘制地图
      districtExplorer: null,
      //文本标记
      text: 'null',
      outClick: null,
      //点标记
      marker: null,
      //默认城市 --- 重庆
      autoComplete: null,
      //切换区域
      switch2AreaNode: null,
      //格式化地图
      formateMap: null,
      //记录当前搜索的名称
      searchName: '',
      textList: [],

      geocoder:null,
    }
  },
  components: {},

  created() {
    if (this.$route.query.cityName) {
      this.isCity = true
    }
  },
  mounted() {
    this.mapInit()
  },
  methods: {
    addLotPoint() {
      this.massMarks.setData(this.pointData)
      this.massMarks.setMap(this.map)
    },
    backHome() {
      this.outClick()
    },
    // 初始加载底图
    mapInit: function() {
      var that = this
      AMapLoader.load({
        key: '7060e76c7045c8344955f5e4e649dc01',
        // 插件集合
        plugin: ['AMap.DistrictSearch', 'AMap.ControlBar', 'AMap.Geocoder'],
        v: '1.4.15',
        // protocol:"",
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        },
        uiVersion: '2.0' //添加 uiVersion 的脚本版本号
      }).then((AMap) => {
        that.map = new AMap.Map('map', {
          center: [106.549509, 29.560767], // [107.755852, 29.590834],
          expandZoomRange: true,
          cursor: 'pointer',
          // zooms: [3, 20],
          dragEnable: true, //拖拽
          zoomEnable: true,  //缩放
          zoom: 5, //8.35,
          pitch: 0, // 地图俯仰角度，有效范围 0 度- 83 度
          viewMode: '3D', // 地图模式
          // mapStyle: 'amap://styles/dae69c38c5ed2e3cdad1dae8e34f7413' // "amap://styles/cf4bbeff185671422895aaff7434766a"
          mapStyle: 'amap://styles/ca9c387f36280f589fc4bd06c9cfcac7' // "amap://styles/cf4bbeff185671422895aaff7434766a"
        })
        AMap.plugin('AMap.Geocoder', function() {
          that.geocoder = new AMap.Geocoder({
            city: '全国'
          })
        })
        that.map.on('zoomchange', function() {
          var zoom = that.map.getZoom() //获取当前地图级别
          if (zoom < 7.5) {
            that.map.setZoom(7.5)
            that.map.setCenter([107.829509, 30.160967])
          }
        })
        // 初始化地图名称显示
        that.showCityName()
        if (that.isCity || that.isDetail) {
          that.clearCityName()
        }
        that.map.on('zoomchange', function() {
          if (that.isCity) {
            return false
          }
          if (that.map.getZoom() <= 9) {
            that.clearCityName()
            that.showCityName()
          } else {
            that.showCityName2()
          }
        })//缩放变化
        // 海量点结束--------------
        //
        // function showCityName(name) {
        //   //只有下面这些城市需要缩放到一定层级才显示城市名称
        //   const cityList = ['南岸区', '大渡口区', '九龙坡区', '南岸区', '渝中区', '江北区']
        //   if (cityList.indexOf(name) > -1 && that.map.getZoom() <= 10) {
        //     return false
        //   }
        //   if (that.text != 'null') {
        //     that.map.remove(that.text)
        //   }
        //
        //   const { position } = citys.find(item => {
        //     return item.name == name
        //   })
        //   that.text = new AMap.Text({
        //     text: name,
        //     anchor: 'center', // 设置文本标记锚点
        //     style: {
        //       'padding': '2px 5px',
        //       'margin-bottom': '1rem',
        //       'border-radius': '.25rem',
        //       'background-color': 'white',
        //       'border-width': 0,
        //       'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
        //       'text-align': 'center',
        //       'font-size': '14px',
        //       'color': 'blue'
        //     },
        //     bubble: true,
        //     position: position
        //   })
        //   that.text.setMap(null)
        //   that.text.setMap(that.map)
        // }

        /**
         *绘制 重庆区域
         * */
        function showCityAll() {
          //main.js加载的模块 DistrictSearch
          AMap.plugin(['AMap.DistrictSearch'], () => {
            // 行政区查询服务
            that.district = new AMap.DistrictSearch({
              subdistrict: 0,
              extensions: 'all',
              level: 'city'
            })

            /**
             * 只显示当前行政区域
             * */
            if (that.polygon2) {
              that.map.remove(that.polygon2)
            }
            //绘制地图，只显示当前行政区域，自定义边境颜色
            that.district.search('重庆', (status, result) => {
              // 外多边形坐标数组和内多边形坐标数组
              var outer = [
                new AMap.LngLat(-360, 90, true),
                new AMap.LngLat(-360, -90, true),
                new AMap.LngLat(360, -90, true),
                new AMap.LngLat(360, 90, true)
              ]
              var holes = result.districtList[0].boundaries
              var pathArray = [outer]
              pathArray.push.apply(pathArray, holes)
              that.polygon = new AMap.Polygon({
                pathL: pathArray,
                strokeColor: '#fff',
                strokeWeight: 1.5,
                fillColor: '#fff',
                fillOpacity: 1
              })
              that.polygon.setPath(pathArray)
              that.map.add(that.polygon)
              that.$emit('loadingSuccess')
            })
          })
        }

        //行政区域操作
        AMapUI.loadUI(['geo/DistrictExplorer'], function(DistrictExplorer) {
          //创建一个实例
          that.districtExplorer = new DistrictExplorer({
            eventSupport: true,
            map: that.map
          })
          /**
           * 全部全部地图
           * */
          //切换区域
          that.switch2AreaNode = function switch2AreaNode (adcode, callback) {
            if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) {
              return
            }
            loadAreaNode(adcode, function(error, areaNode) {
              if (error) {
                if (callback) {
                  callback(error)
                }
                return
              }
              currentAreaNode = window.currentAreaNode = areaNode
              that.$emit('handleClickRegion', currentAreaNode)
              //设置当前使用的定位用节点
              that.districtExplorer.setAreaNodesForLocating([currentAreaNode])
              refreshAreaNode(areaNode)
              if (callback) {
                callback(null, areaNode)
              }
            })
          }
          that.formateMap =  function formateMap() {
            var adcode = 500000
            that.districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
              //更新地图视野
              that.map.setBounds(areaNode.getBounds(), null, null, true)
              //清除已有的绘制内容
              that.districtExplorer.clearFeaturePolygons()
              //绘制子区域
              that.districtExplorer.renderSubFeatures(areaNode, function(feature, i) {
                var fillColor = colors[i % colors.length]
                // var strokeColor = colors[colors.length - 1 - i % colors.length];
                var strokeColor = colors[i % colors.length]
                return {
                  cursor: 'default',
                  bubble: true,
                  strokeColor: strokeColor, //线颜色
                  strokeOpacity: 1, //线透明度
                  strokeWeight: 1, //线宽
                  fillColor: fillColor, //填充色
                  fillOpacity: .9 //填充透明度
                }
              })

              //绘制父区域
              that.districtExplorer.renderParentFeature(areaNode, {
                cursor: 'default',
                bubble: true,
                strokeColor: 'black', //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: null, //填充色
                fillOpacity: 0.5 //填充透明度
              })
              that.map.setZoom(7.5)
            })
          }


          /**
           * 初始化地图
           * */
          that.switch2AreaNode(500000)
          showCityAll()
          that.formateMap()



          /**
           * 初始化绘制地图
           * */
          //监听feature的hover事件
          that.districtExplorer.on('featureMouseover', function(e, feature) {
            const name = feature.properties.name
            const position = [feature.properties.center[0], feature.properties.center[1]]
            if (!that.isCity) {
              toggleHoverFeature(feature, e.type === 'featureMouseover',
                e.originalEvent ? e.originalEvent.lnglat : null)
              // showCityName(name, position)
            }
          })
          //移出监听feature的事件
          that.districtExplorer.on('featureMouseout', function(e, feature) {
            that.map.remove(that.text)
            if (!that.isCity ) {
              toggleHoverFeature(feature, e.type === 'featureMouseover',
                e.originalEvent ? e.originalEvent.lnglat : null)
            }

          })
          //监听鼠标在feature上滑动
          that.districtExplorer.on('featureMousemove', function(e, feature) {
            //更新提示位置
            tipMarker.setPosition(e.originalEvent.lnglat)
          })

          //feature被点击 内部被点击
          that.districtExplorer.on('featureClick', function(e, feature) {
            if (that.isCity ) {
              //记录城市code
              console.log(feature.properties.adcode,"eee")
              //点击内部，获取经纬度，显示点标记
              const x = e.originalEvent.lnglat.lng
              const y = e.originalEvent.lnglat.lat
              that.choicePosition(e.originalEvent.lnglat.lng, e.originalEvent.lnglat.lat,feature.properties.adcode)
            } else {
              var props = feature.properties
              that.isCity = true
              //如果存在子节点
              // if (props.childrenNum > 0) {
              //切换聚焦区域
              that.switch2AreaNode(props.adcode)
            }
            // }
          })

          that.outClick = function outClick() {
            that.isCity = false
            that.$emit('changeTitle', '')
            that.switch2AreaNode(500000)
            showCityAll()
            that.formateMap()
          }
          //外部区域被点击
          that.districtExplorer.on('outsideClick', function(e) {
            that.$emit('resetCityInfo')
            that.districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) {
              if (that.isDetail) {
                return
              }
              if (routeFeatures && routeFeatures.length > 1) {
                //切换到省级区域
                that.outClick()
                //清空当前搜索的区域名称
                that.searchName = null
              } else {
                //切换到全国
                that.switch2AreaNode(100000)
              }
            }, {
              levelLimit: 2
            })
          })

          //当前聚焦的区域
          //当前聚焦的区域
          var currentAreaNode = null
          //鼠标hover提示内容
          var $tipMarkerContent = $('<div class="tipMarker top"></div>')
          var tipMarker = new AMap.Marker({
            content: $tipMarkerContent.get(0),
            offset: new AMap.Pixel(0, 0),
            bubble: true
          })

          //根据Hover状态设置相关样式
          function toggleHoverFeature(feature, isHover, position) {
            tipMarker.setMap(isHover ? that.map : null)
            if (!feature) {
              return
            }
            var props = feature.properties
            if (isHover) {
              //更新提示内容
              $tipMarkerContent.html(' ')
              //更新位置
              tipMarker.setPosition(position || props.center)
            }
            $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover)
            //更新相关多边形的样式
            var polys = that.districtExplorer.findFeaturePolygonsByAdcode(props.adcode)
            for (var i = 0, len = polys.length; i < len; i++) {
              polys[i].setOptions({
                fillOpacity: isHover ? 0.6 : 0.9
              })
            }
          }

          //搜索坐标定位
          AMap.plugin('AMap.Autocomplete', function() {
            // 实例化Autocomplete

          })

          //绘制某个区域的边界
          function renderAreaPolygons(areaNode) {
            //更新地图视野
            that.map.setBounds(areaNode.getBounds(), null, null, true)
            //清除已有的绘制内容
            that.districtExplorer.clearFeaturePolygons()
            let adcode = areaNode._data.geoData.parent.properties.adcode
            if (adcode == '500000') {
              return
            }
            AMap.plugin(['AMap.DistrictSearch'], () => {
              // 行政区查询服务
              var district = new AMap.DistrictSearch({
                subdistrict: 0,
                extensions: 'all',
                level: 'biz_area'
              })
              //绘制地图，只显示当前行政区域，自定义边境颜色
              district.search(adcode.toString(), (status, result) => {
                // 外多边形坐标数组和内多边形坐标数组
                var outer = [
                  new AMap.LngLat(-360, 90, true),
                  new AMap.LngLat(-360, -90, true),
                  new AMap.LngLat(360, -90, true),
                  new AMap.LngLat(360, 90, true)
                ]
                var holes = result.districtList[0].boundaries
                var pathArray = [outer]
                pathArray.push.apply(pathArray, holes)

                that.polygon2 = new AMap.Polygon({
                  pathL: pathArray,
                  strokeColor: '#0469c1',
                  strokeWeight: 1.5,
                  fillColor: '#123553',
                  fillOpacity: .9,
                  bubble: true
                })
                that.polygon2.setPath(pathArray)
                that.map.add(that.polygon2)
              })
            })
          }

          //切换区域后刷新显示内容
          function refreshAreaNode(areaNode) {
            that.districtExplorer.setHoverFeature(null)
            renderAreaPolygons(areaNode)
          }


          //加载区域
          function loadAreaNode(adcode, callback) {
            that.districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
              if (error) {
                if (callback) {
                  callback(error)
                }
                return
              }
              // renderAreaPanel(areaNode);
              if (callback) {
                callback(null, areaNode)
              }
            })
          }

        })

      }).catch(e => {
        console.log(e)
      })
    },
    choicePosition(x, y,code) {
      this.$emit('showPosition', x, y,code)
      if (this.marker) {
        this.map.remove(this.marker)
      }
      this.marker = new AMap.Marker({
        icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        position: [x, y],
        imageSize: new AMap.Size(10, 10),
        offset: new AMap.Pixel(-20, -62)
      })
      this.marker.setMap(this.map)
    },
    //查找坐标
    searchPosition(address) {
      console.log(address, 'address')
      var that = this

      this.geocoder.getLocation(address, function(status, result) {
        console.log(result.geocodes[0].adcode, 'result.geocodes[0].adcode')
        const adcode = result.geocodes[0].adcode

        if(that.searchName == adcode){
          return
        }
        that.searchName = adcode

        that.outClick()
        that.isCity = true
        that.switch2AreaNode(adcode)
        if (status === 'complete' && result.info === 'OK') {
          const geocode = result.geocodes[0]
          that.map.setZoomAndCenter(15, [geocode.location.lng, geocode.location.lat])
          that.choicePosition(geocode.location.lng, geocode.location.lat,adcode)
        }
      })
    },
    //清除所有城市的名称
    clearCityName() {
      this.textList.forEach((item, index) => {
        this.map.remove(this.textList[index])
      })
    },
    //1。不显示被隐藏的城市名称
    showCityName() {
      //只有下面这些城市需要缩放到一定层级才显示城市名称
      citys.forEach((item, index) => {
        this.textList.push(new AMap.Text({
          text: item.name,
          anchor: 'center', // 设置文本标记锚点
          style: {
            'background-color': 'rgba(0,0,0,0)',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'color': '#000'
          },
          bubble: true,
          position: item.position
        }))
        this.textList[this.textList.length - 1].setMap(null)
        this.textList[this.textList.length - 1].setMap(this.map)
      })
    },
    //2。显示被隐藏的城市名称
    showCityName2() {
      let citys1 = citys.concat(citys2)
      citys1.forEach((item, index) => {
        this.textList.push(new AMap.Text({
          text: item.name,
          anchor: 'center', // 设置文本标记锚点
          style: {
            'background-color': 'rgba(0,0,0,0)',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'color': '#000'
          },
          bubble: true,
          position: item.position
        }))
        this.textList[this.textList.length - 1].setMap(null)
        this.textList[this.textList.length - 1].setMap(this.map)
      })
    },
  },
  destroyed() {
    this.map.destroy( );
  }

}
</script>
<style>

</style>
<style lang="scss">


.amap-logo {
  display: none;
  opacity: 0 !important;
}

.amap-copyright {
  opacity: 0;
}


.tipMarker {
  display: flex;
  background: #fff;
}
</style>
